﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Evan.Config
{
    public class ConfigHelper
    {
        /// <summary>
        /// 获取配置项值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="xmlName"></param>
        /// <returns></returns>
        public static string GetConfigItem(string name, string xmlName = "configs.xml")
        {
            XDocument document = XDocument.Load(string.Format(@"{0}\configs\" + xmlName));
            var query = from m in document.Elements("configs").Elements(name)
                        select m;
            return query.First().Value;
        }
        /// <summary>
        /// 设置配置项值
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="xmlName"></param>
        public static void SetConfigItem(string name, string value, string xmlName = "configs.xml")
        {
            try
            {
                string filepath = string.Format(@"{0}\configs\" + xmlName);
                XDocument document = XDocument.Load(filepath);
                var query = from m in document.Elements("configs").Elements(name)
                            select m;
                if (query.Count() > 0)
                {
                    XElement ele = query.First<XElement>();
                    ele.Value = value;
                    document.Save(filepath);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("ConfigHelper.SetConfigItem", ex);
            }
        }


        /// <summary>  
        /// 根据Key取Value值  
        /// </summary>  
        /// <param name="key"></param>  
        public static string GetValue(string key)
        {
            return ConfigurationManager.AppSettings[key].ToString().Trim();
        }

    }
}
